package com.bootdo.clouddoactiviti.controller;

import com.bootdo.clouddoactiviti.vo.taskDo;
import com.bootdo.clouddocommon.constants.CommonConstants;
import com.bootdo.clouddocommon.context.FilterContextHandler;
import com.bootdo.clouddocommon.dto.UserToken;
import com.bootdo.clouddocommon.utils.JwtUtils;
import com.bootdo.clouddocommon.utils.PageUtils;
import com.bootdo.clouddocommon.utils.R;
import com.bootdo.clouddocommon.utils.StringUtils;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.ProcessDiagramGenerator;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/task")
public class taskController {
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private HistoryService historyService;
    @GetMapping("/queryTask")
    R queryTask(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        System.out.println(">>>>>>>>>>"+request.getHeader(CommonConstants.CONTEXT_TOKEN));
        UserToken user= JwtUtils.getInfoFromToken(request.getHeader(CommonConstants.CONTEXT_TOKEN));
        //创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        //办理人的任务列表
        List<Task> list = taskQuery.processVariableValueEquals("userid",user.getUserId()).taskDefinitionKey("usertask1")//根据流程创建人员显示任务列表
                .list();
        //遍历任务列表
        List<taskDo> mylist = new ArrayList<taskDo>();
        if(list!=null&&list.size()>0){
            for(Task task:list){
                taskDo p = new taskDo();
                p.setId(task.getId());
                p.setName(task.getName());
                p.setCreater(user.getUsername());
                p.setProcessDefinitionId(task.getProcessDefinitionId());
                p.setpProcessInstanceId(task.getProcessInstanceId());
                p.setResourceName(repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult().getResourceName());
                mylist.add(p);
            }
        }
        int total = mylist.size();
        int start=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString())-1);
        int end=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString()));
        if(end>total){
            end=total;
        }
        PageUtils pageUtils = new PageUtils(mylist.subList(start, end), total);
        return R.ok().put("data",pageUtils);
    }
    @GetMapping("/applyTask")
   R compileTask(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        UserToken user= JwtUtils.getInfoFromToken(request.getHeader(CommonConstants.CONTEXT_TOKEN));
        Map<String,Object> variables = new HashMap<String,Object>();

        if(params.get("money")==null){
            variables.put("leave_type",params.get("leave_type") );
            variables.put("reason",params.get("reason") );
        }else{
            variables.put("money",params.get("money") );
        }

        taskService.setOwner(params.get("taskid").toString(),user.getUsername());
        taskService.complete(params.get("taskid").toString(),variables);
        return  R.ok("任务申请完毕");
    }
    @GetMapping("/queryapproveTask")
    R queryapproveTask(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {

        UserToken user= JwtUtils.getInfoFromToken(request.getHeader(CommonConstants.CONTEXT_TOKEN));
        //创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        //办理人的任务列表
        List<Task> list = taskQuery.taskAssigneeIds(Arrays.asList(user.getRolenames().split(",")))//根据流程创建人员显示任务列表
                .list();
        //遍历任务列表
        List<taskDo> mylist = new ArrayList<taskDo>();
        if(list!=null&&list.size()>0){
            for(Task task:list){
                taskDo p = new taskDo();
                p.setId(task.getId());
                p.setName(task.getName());
                p.setCreater(user.getUsername());
                p.setProcessDefinitionId(task.getProcessDefinitionId());
                p.setpProcessInstanceId(task.getProcessInstanceId());
                p.setResourceName(repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult().getResourceName());
                mylist.add(p);
            }
        }
        int total = mylist.size();
        int start=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString())-1);
        int end=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString()));
        if(end>total){
            end=total;
        }
        PageUtils pageUtils = new PageUtils(mylist.subList(start, end), total);
        return R.ok().put("data",pageUtils);
    }
    /*获取流程变量*/
    @GetMapping("/getTaskvariables")
    R getTaskvariables(@RequestParam Map<String, Object> params){
        Map<String, Object> variablesMap = new HashMap<String, Object>();
        variablesMap = taskService.getVariables(params.get("id").toString());
        return R.ok().put("data",variablesMap);
    }
    @GetMapping("/approveTask")
    R approveTask(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        UserToken user= JwtUtils.getInfoFromToken(request.getHeader(CommonConstants.CONTEXT_TOKEN));
        Map<String,Object> variables = new HashMap<String,Object>();
        variables.put("approvalopinion",params.get("approvalopinion"));
        System.out.println("任务id"+params.get("taskid").toString()+"审批意见为》》》"+params.get("approvalopinion"));
        taskService.setOwner(params.get("taskid").toString(),user.getUsername());
        taskService.complete(params.get("taskid").toString(),variables);
        System.out.println("任务审批完毕");
        return R.ok();
    }
    @GetMapping("/queryHistoryTask")
   R queryHistoryTask(@RequestParam Map<String, Object> params,HttpServletRequest request) throws Exception {
        UserToken user= JwtUtils.getInfoFromToken(request.getHeader(CommonConstants.CONTEXT_TOKEN));
        System.out.println(user);
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery().taskOwner(user.getUsername())
                .list();
        List<taskDo> mylist = new ArrayList<taskDo>();
        if(list!=null&&list.size()>0){
            for(HistoricTaskInstance temp:list){
                taskDo p = new taskDo();
                p.setId(temp.getId());
                p.setName(temp.getName());
                p.setpProcessInstanceId(temp.getProcessInstanceId());
                p.setProcessDefinitionId(temp.getProcessDefinitionId());
                p.setResourceName(repositoryService.createProcessDefinitionQuery().processDefinitionId(temp.getProcessDefinitionId()).singleResult().getResourceName());
                mylist.add(p);
            }
        }
        int total = mylist.size();
        int start=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString())-1);
        int end=Integer.parseInt(params.get("limit").toString())*(Integer.parseInt(params.get("page").toString()));
        if(end>total){
            end=total;
        }
        PageUtils pageUtils = new PageUtils(mylist.subList(start, end), total);
        return R.ok().put("data",pageUtils);
    }

    @GetMapping("/querytaskimage")
    public void readResource(String processDefinitionId,String pProcessInstanceId, HttpServletResponse response)
            throws Exception {
        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
System.out.println(processDefinitionId+">>>>>>>>>>>>"+pProcessInstanceId);


        ProcessDefinition processDefinition =  repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();

        if(StringUtils.isEmpty(pProcessInstanceId) == false)
        {
            getActivitiProccessImage(pProcessInstanceId,response);
            //ProcessDiagramGenerator.generateDiagram(pde, "png", getRuntimeService().getActiveActivityIds(processInstanceId));
        }
        else
        {

            // 通过接口读取
            InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId() ,processDefinition.getDiagramResourceName());

            // 输出资源内容到相应对象
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
        }
    }


    /**
     * 获取流程图像，已执行节点和流程线高亮显示
     */
    public void getActivitiProccessImage(String pProcessInstanceId, HttpServletResponse response)
    {
        //logger.info("[开始]-获取流程图图像");
        try {
            //  获取历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(pProcessInstanceId).singleResult();

            if (historicProcessInstance == null) {
                //throw new BusinessException("获取流程实例ID[" + pProcessInstanceId + "]对应的历史流程实例失败！");
            }
            else
            {
                // 获取流程定义
                ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                        .getDeployedProcessDefinition(historicProcessInstance.getProcessDefinitionId());

                // 获取流程历史中已执行节点，并按照节点在流程中执行先后顺序排序
                List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery()
                        .processInstanceId(pProcessInstanceId).orderByHistoricActivityInstanceId().desc().list();

                // 已执行的节点ID集合
                List<String> executedActivityIdList = new ArrayList<String>();
                int index = 1;
                String onlinetask = "";
                //logger.info("获取已经执行的节点ID");
                for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
                    if(index == 1){
                        onlinetask=activityInstance.getActivityId();
                        executedActivityIdList.add(activityInstance.getActivityId()+"#");
                    }else {
                        if(onlinetask.equals(activityInstance.getActivityId())){
                            executedActivityIdList.add(activityInstance.getActivityId()+"#");
                        }else{
                        executedActivityIdList.add(activityInstance.getActivityId());
                        }
                    }//获取当前节点，当前节点加#非当前节点不加#
                    //logger.info("第[" + index + "]个已执行节点=" + activityInstance.getActivityId() + " : " +activityInstance.getActivityName());
                    index++;
                }

                BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());

                // 已执行的线集合
                List<String> flowIds = new ArrayList<String>();
                // 获取流程走过的线 (getHighLightedFlows是下面的方法)
                flowIds = getHighLightedFlows(bpmnModel,processDefinition, historicActivityInstanceList);


                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                // 获取流程图图像字符流
                ProcessDiagramGenerator pec = processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator();

                //配置字体
                InputStream imageStream = pec.generateDiagram(bpmnModel, "png", executedActivityIdList, flowIds,"宋体","微软雅黑","黑体",null,2.0);


System.out.println("111111111"+executedActivityIdList);
                response.setContentType("image/png");
                OutputStream os = response.getOutputStream();
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = imageStream.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                imageStream.close();
            }
            //logger.info("[完成]-获取流程图图像");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            //logger.error("【异常】-获取流程图失败！" + e.getMessage());
            //throw new BusinessException("获取流程图失败！" + e.getMessage());
        }
    }

    public List<String> getHighLightedFlows(BpmnModel bpmnModel, ProcessDefinitionEntity processDefinitionEntity, List<HistoricActivityInstance> historicActivityInstances)
    {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //24小时制
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId

        for (int i = 0; i < historicActivityInstances.size() - 1; i++)
        {
            // 对历史流程节点进行遍历
            // 得到节点定义的详细信息
            FlowNode activityImpl = (FlowNode)bpmnModel.getMainProcess().getFlowElement(historicActivityInstances.get(i).getActivityId());


            List<FlowNode> sameStartTimeNodes = new ArrayList<FlowNode>();// 用以保存后续开始时间相同的节点
            FlowNode sameActivityImpl1 = null;

            HistoricActivityInstance activityImpl_ = historicActivityInstances.get(i);// 第一个节点
            HistoricActivityInstance activityImp2_ ;

            for(int k = i + 1 ; k <= historicActivityInstances.size() - 1; k++)
            {
                activityImp2_ = historicActivityInstances.get(k);// 后续第1个节点

                if ( activityImpl_.getActivityType().equals("userTask") && activityImp2_.getActivityType().equals("userTask") &&
                        df.format(activityImpl_.getStartTime()).equals(df.format(activityImp2_.getStartTime()))   ) //都是usertask，且主节点与后续节点的开始时间相同，说明不是真实的后继节点
                {

                }
                else
                {
                    sameActivityImpl1 = (FlowNode)bpmnModel.getMainProcess().getFlowElement(historicActivityInstances.get(k).getActivityId());//找到紧跟在后面的一个节点
                    break;
                }

            }
            sameStartTimeNodes.add(sameActivityImpl1); // 将后面第一个节点放在时间相同节点的集合里
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++)
            {
                HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1);// 后续第二个节点

                if (df.format(activityImpl1.getStartTime()).equals(df.format(activityImpl2.getStartTime()))  )
                {// 如果第一个节点和第二个节点开始时间相同保存
                    FlowNode sameActivityImpl2 = (FlowNode)bpmnModel.getMainProcess().getFlowElement(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                }
                else
                {// 有不相同跳出循环
                    break;
                }
            }
            List<SequenceFlow> pvmTransitions = activityImpl.getOutgoingFlows() ; // 取出节点的所有出去的线

            for (SequenceFlow pvmTransition : pvmTransitions)
            {// 对所有的线进行遍历
                FlowNode pvmActivityImpl = (FlowNode)bpmnModel.getMainProcess().getFlowElement( pvmTransition.getTargetRef());// 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }

        }
        return highFlows;

    }
    @GetMapping("getToken")
    public R getToken() {
        return R.ok().put("token", FilterContextHandler.getToken()).put("url", "http://localhost:8002/api-exam/exam/upload")
                .put("key", UUID.randomUUID().toString());
    }
}
